import React, { useState, useEffect } from 'react';
import { Table, message, Button, Popconfirm, Space, DatePicker, Dropdown, Menu } from 'antd';
import { MoreOutlined } from '@ant-design/icons';
import { getBorrowList, deleteBorrow, returnAsset, updateBorrowStatus, permitUpdate, updateBorrow } from '../../../services/api';
import moment from 'moment';
import 'moment/locale/zh-cn';
import BorrowStatusFilter from '../../Filter/BorrowStatusFilter';

const BorrowList = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [statusFilter, setStatusFilter] = useState(null);
  const [editingBorrowId, setEditingBorrowId] = useState(null);

  // 获取当前管理员信息
  const currentUser = JSON.parse(sessionStorage.getItem('user') || '{}');
  const isAdmin = currentUser.admin === 'yes';

  // 设置 moment 为中文
  moment.locale('zh-cn');

  const formatDate = (dateString) => {
    if (!dateString) return '';
    
    // 如果是中文格式的日期，先用 moment 解析
    if (typeof dateString === 'string' && dateString.includes('月')) {
      const m = moment(dateString, 'MMMM DD, YYYY', 'zh-cn');
      if (m.isValid()) {
        return m.format('YYYY-MM-DD');
      }
    }
    
    // 如果是长整数形式的时间戳字符串，需要转换为数字
    if (typeof dateString === 'string' && !isNaN(dateString)) {
      return moment(parseInt(dateString)).format('YYYY-MM-DD');
    }
    
    // 如果已经是数字类型的时间戳
    if (typeof dateString === 'number') {
      return moment(dateString).format('YYYY-MM-DD');
    }
    
    // 其他情况尝试直接解析
    const m = moment(dateString);
    if (m.isValid()) {
      return m.format('YYYY-MM-DD');
    }
    
    return '';
  };

  const fetchBorrowList = async () => {
    setLoading(true);
    try {
      const response = await getBorrowList();
      if (response.code === 200) {
        // 打印原始数据
        console.log("原始返回数据:", response.data);
        
        // 格式化日期
        const formattedData = response.data.map(item => {
          const formatted = {
            ...item,
            borrowTime: formatDate(item.borrowTime),
            expectedReturnTime: formatDate(item.expectedReturnTime),
            actualReturnTime: formatDate(item.actualReturnTime)
          };
          // 打印每条记录的用户名
          console.log("记录ID:", formatted.borrowId, "用户名:", formatted.u_name);
          return formatted;
        });
        setData(formattedData);
        console.log("打印返回结果", formattedData);
      } else {
        message.error(response.message || '获取借用列表失败');
      }
    } catch (error) {
      console.error('获取借用列表失败:', error);
      message.error('获取借用列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchBorrowList();
  }, []);

  // 添加筛选效果
  useEffect(() => {
    if (statusFilter) {
      setFilteredData(data.filter(item => item.borrowStatus === statusFilter));
    } else {
      setFilteredData(data);
    }
  }, [statusFilter, data]);

  const handleDelete = async (record) => {
    if (record.borrowStatus === '借用中') {
      message.error('正在使用中的记录不能删除');
      return;
    }
    
    if (!record.borrowId) {
      message.error('借用记录ID不存在');
      return;
    }

    try {
      // 打印ID用于调试
      console.log('删除的借用记录ID:', record.borrowId);
      
      // 先检查记录是否存在
      const response = await deleteBorrow(record.borrowId);
      if (response.code === 200) {
        message.success('删除成功');
        fetchBorrowList();  // 刷新列表
      } else if (response.message === '借用记录不存在') {
        message.error('该记录可能已被删除，将为您刷新列表');
        fetchBorrowList();  // 刷新列表
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 处理归还
  const handleReturn = async (record) => {
    try {
      // 先更新借用状态为已归还
      const updateStatusResponse = await updateBorrowStatus(record.borrowId, {
        borrowStatus: '已归还'
      });

      if (updateStatusResponse.code === 200) {
        // 更新资产数量，增加可用数量
        const updateAssetResponse = await permitUpdate(record.assetId, {
          assetNum: record.borrowNum,  
          assetStatus: 'return' // 操作类型：归还
        });

        if (updateAssetResponse.code === 200) {
          message.success('归还成功');
          fetchBorrowList();  // 刷新列表
        } else {
          // 如果更新资产数量失败，回滚借用状态
          await updateBorrowStatus(record.borrowId, {
            borrowStatus: '借用中'
          });
          message.error('更新资产数量失败');
        }
      } else {
        message.error(updateStatusResponse.message || '更新借用状态失败');
      }
    } catch (error) {
      console.error('归还失败:', error);
      message.error('归还失败');
    }
  };

  // 处理日期修改
  const handleDateChange = async (record, date) => {
    try {
      const formattedDate = date ? date.format('YYYY-MM-DD') : null;
      if (!formattedDate) {
        message.error('请选择有效的日期');
        return;
      }

      // 获取当前记录的完整信息
      const currentBorrow = await getBorrowList();
      const borrowRecord = currentBorrow.data.find(item => item.borrowId === record.borrowId);
      
      if (!borrowRecord) {
        message.error('找不到借用记录');
        return;
      }

      // 确保所有日期都使用YYYY-MM-DD格式，并且不发送空字符串
      const formattedBorrowRecord = {
        borrowId: borrowRecord.borrowId,
        uId: borrowRecord.uId,
        assetId: borrowRecord.assetId,
        borrowNum: borrowRecord.borrowNum,
        borrowStatus: borrowRecord.borrowStatus,
        borrowTime: formattedDate,
        expectedReturnTime: formatDate(borrowRecord.expectedReturnTime) || null,
        actualReturnTime: formatDate(borrowRecord.actualReturnTime) || null,
        borrowReason: borrowRecord.borrowReason
      };

      // 移除值为null的字段
      Object.keys(formattedBorrowRecord).forEach(key => {
        if (formattedBorrowRecord[key] === null) {
          delete formattedBorrowRecord[key];
        }
      });

      // 更新借用时间
      const response = await updateBorrow(record.borrowId, formattedBorrowRecord);

      if (response.code === 200) {
        message.success('借用时间修改成功');
        setEditingBorrowId(null);
        fetchBorrowList();
      } else {
        message.error(response.message || '修改失败');
      }
    } catch (error) {
      console.error('修改日期失败:', error);
      message.error('修改日期失败');
    }
  };

  const columns = [
    {
      title: '借用ID',
      dataIndex: 'borrowId',
      key: 'borrowId',
    },
    {
      title: '借用人',
      dataIndex: 'uName',
      key: 'uName',
    },
    {
      title: '所属部门',
      dataIndex: 'depName',
      key: 'depName',
    },
    {
      title: '资产名称',
      dataIndex: 'assetName',
      key: 'assetName',
    },
    {
      title: '借用状态',
      dataIndex: 'borrowStatus',
      key: 'borrowStatus',
    },
    {
      title: '借用数量',
      dataIndex: 'borrowNum',
      key: 'borrowNum',
    },
    {
      title: '借用时间',
      dataIndex: 'borrowTime',
      key: 'borrowTime',
      render: (text, record) => {
        if (isAdmin && editingBorrowId === record.borrowId) {
          return (
            <DatePicker
              defaultValue={text ? moment(text) : null}
              onChange={(date) => handleDateChange(record, date)}
              onBlur={() => setEditingBorrowId(null)}
              autoFocus
            />
          );
        }
        return text;
      }
    },
    {
      title: '预计归还时间',
      dataIndex: 'expectedReturnTime',
      key: 'expectedReturnTime',
    },
    {
      title: '实际归还时间',
      dataIndex: 'actualReturnTime',
      key: 'actualReturnTime',
    },
    {
      title: '备注',
      dataIndex: 'borrowReason',
      key: 'borrowReason',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        const menu = (
          <Menu>
            {record.borrowStatus === '借用中' && record.uId === currentUser.uId && (
              <Menu.Item key="return">
                <Popconfirm
                  title="确定要归还这个资产吗？"
                  onConfirm={() => handleReturn(record)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="link">归还</Button>
                </Popconfirm>
              </Menu.Item>
            )}
            {isAdmin && (
              <Menu.Item key="editDate">
                <Button 
                  type="link"
                  onClick={() => setEditingBorrowId(record.borrowId)}
                >
                  修改借用时间
                </Button>
              </Menu.Item>
            )}
            {(record.borrowStatus === '借用中' ||
              record.borrowStatus === '已归还' ||
              record.borrowStatus === '已拒绝' || 
              record.borrowStatus === '待审批') && (
              <Menu.Item key="delete">
                <Popconfirm
                  title="确定要删除这条记录吗？"
                  onConfirm={() => handleDelete(record)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="link" danger>
                    删除
                  </Button>
                </Popconfirm>
              </Menu.Item>
            )}
          </Menu>
        );

        // 只有当有可用操作时才显示下拉菜单
        const hasOperations = (
          (record.borrowStatus === '借用中' && record.uId === currentUser.uId) ||
          (isAdmin && record.borrowStatus === '借用中') ||
          record.borrowStatus !== '借用中'
        );

        return hasOperations ? (
          <Dropdown overlay={menu} trigger={['click']}>
            <Button type="link">
              <MoreOutlined />
            </Button>
          </Dropdown>
        ) : null;
      },
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <h2>借用列表</h2>
      <div style={{ marginBottom: 16 }}>
        <BorrowStatusFilter
          value={statusFilter}
          onChange={setStatusFilter}
        />
      </div>
      <Table
        columns={columns}
        dataSource={filteredData}
        rowKey="borrowId"
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
        loading={loading}
      />
    </div>
  );
};

export default BorrowList; 